//
//  MainViewController.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/7/3.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJExtension

class MainViewController: UIViewController {

    fileprivate var homeAdView: HomeADView = HomeADView()
    
    fileprivate var rightItem: UIButton?
    fileprivate let userDefault = UserDefaults.standard
    fileprivate var TYPE: Int = 0
    
    fileprivate lazy var contentView: UIView = UIView() // 9宫格的父视图
    fileprivate var topicView: UIView? // 环球头条的父视图
    fileprivate lazy var redianLabel: UILabel = UILabel() // 热点
    fileprivate var marquee: SXMarquee? // 跑马灯
    
    fileprivate let orderResult = (order:"?orderResult=0",payment :"?orderResult=1" ,cancle : "?orderResult=2") // 商家
    fileprivate let tecOrderResult = (order:"?orderResult=0",payment :"?orderResult=1" ,cancle : "?orderResult=2") // 技师
    
    fileprivate var storeDetailModel: HomeStoreDetailModel?
    
    
    // 头部视图
    fileprivate lazy var storeNameView: UIView = {
        let sv = UIView()
        sv.backgroundColor = UIColor(r: 0, g: 184, b: 255)
        return sv
    }()
    // 店铺图片
    fileprivate lazy var storeIcon: UIImageView = {
        let icon = UIImageView(imageName: "wingzero08")
        icon.layer.cornerRadius = 28.5 * WIDTH_SCALE
        icon.layer.masksToBounds = true
        return icon
    }()
    // 店铺标题
    fileprivate lazy var storeNameLabel: UILabel = {
        let label = UILabel(color: UIColor.white, lines: 1)
        let nameString = "湖北骏马旗舰店"
        let nameSize: CGSize = StringSize(nameString as NSString, fontSize: 18 * HEIGHT_SCALE)
        label.text = nameString
        return label
    }()
    // 店铺类型
    fileprivate lazy var storeType: UILabel = {
        let label = UILabel(color: UIColor(r:0, g:184, b: 255), lines: 1)
        label.layer.cornerRadius = 2*HEIGHT_SCALE
        label.layer.masksToBounds = true
        label.backgroundColor = UIColor.clear
        label.text = "洗车店"
        label.font = UIFont.systemFont(ofSize: 10*HEIGHT_SCALE)
        label.textAlignment = NSTextAlignment.center
        return label
    }()
    // 评分星星
    fileprivate lazy var starView: StarView = {
        let starView = StarView()
//        starView.backgroundColor = UIColor.blue
        let startCount: CGFloat = 3.2
        starView.setStar(startCount)
        return starView
    }()
    fileprivate lazy var starLabel: UILabel = {
        let label = UILabel()
        let starCount = 3.2
        return label
    }()
    fileprivate lazy var detailBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(detailBtnClick), for: .touchUpInside)
        return btn
    }()
    fileprivate lazy var btnTitleLabel: UILabel = {
        let label = UILabel()
        return label
    }()
    
    // 9宫格相关属性
    fileprivate lazy var nopayLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.red
        label.font = UIFont.systemFont(ofSize: 11*HEIGHT_SCALE)
        label.textColor = UIColor.white
        label.textAlignment = NSTextAlignment.center
        label.layer.cornerRadius = 7.5
        label.layer.masksToBounds = true
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor(r: 249, g: 249, b: 249)
        
        setupNav()
        
        setupTopHeader()
        
        // 接收到通知 初始化UI
        setupNoti()
        
        checkAutoLogin()
        
        // 动画条
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillEnterForeground, object: nil, queue: OperationQueue.main) { (Notification) in
            self.marquee?.start()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.colorWithHexString("185898")]
        // 跑马灯动画
        setupAnimation()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.marquee?.start()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - init code
extension MainViewController {
    fileprivate func setupNav() {
        title = "版本号: \(AppDelegate().App_Version)"
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.isTranslucent = false
        
        let btn = UIButton()
        btn.setImage(UIImage(named: "jiahao"), for: .normal)
        btn.setImage(UIImage(named: "jiahao"), for: .highlighted)
        btn.sizeToFit()
        btn.addTarget(self, action: #selector(rightBarItemClick), for: .touchUpInside)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
        rightItem = btn
    }
    
    fileprivate func setupTopHeader() {
        
        view.addSubview(storeNameView)
        storeNameView.addSubview(storeIcon)
        storeNameView.addSubview(storeNameLabel)
        storeNameView.addSubview(storeType)
        storeNameView.addSubview(starView)
        storeNameView.addSubview(starLabel)
        storeNameView.addSubview(detailBtn)
        detailBtn.addSubview(btnTitleLabel)
        
        storeNameView.snp.makeConstraints { (make) in
            make.width.equalTo(kScreenW)
            make.top.equalTo(self.view)
            make.left.equalTo(self.view)
            make.height.equalTo(85*HEIGHT_SCALE)
        }
        
        storeIcon.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 57*WIDTH_SCALE, height: 57*WIDTH_SCALE))
            make.centerY.equalTo(self.storeNameView)
            make.left.equalTo(20*WIDTH_SCALE)
        }
        
        let nameString = "湖北骏马旗舰店"
        let nameSize: CGSize = StringSize(nameString as NSString, fontSize: 18 * HEIGHT_SCALE)
        storeNameLabel.text = nameString
        storeNameLabel.snp.makeConstraints { (make) in
            make.left.equalTo((self.storeIcon.snp.right)).offset(14)
            make.top.equalTo(self.storeNameView).offset(9)
            make.size.equalTo(CGSize(width:nameSize.width+5, height:18*HEIGHT_SCALE))
        }
        
        storeType.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width:32*WIDTH_SCALE, height:11*HEIGHT_SCALE))
            make.left.equalTo(self.storeNameLabel.snp.right).offset(5*WIDTH_SCALE)
            make.top.equalTo(self.storeNameLabel)
        }
        
        starView.snp.makeConstraints { (make) in
            make.top.equalTo(self.storeNameLabel.snp.bottom).offset(10*HEIGHT_SCALE)
            make.left.equalTo(self.storeNameLabel)
            make.size.equalTo(CGSize(width:96.5, height:13))
        }
        
        starLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.starView.snp.right).offset(11*WIDTH_SCALE)
            make.centerY.equalTo(self.starView.snp.centerY)
            make.height.equalTo(15*HEIGHT_SCALE)
            make.width.equalTo(80*WIDTH_SCALE)
        }
        
        detailBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.storeNameLabel)
            make.top.equalTo(self.starView.snp.bottom).offset(10*HEIGHT_SCALE)
            make.size.equalTo(CGSize(width:kScreenW-(100*WIDTH_SCALE), height:15))
        }
        
        btnTitleLabel.snp.makeConstraints { (make) in
            make.size.equalTo(self.detailBtn)
            make.center.equalTo(self.detailBtn)
            make.left.equalTo(self.storeNameLabel)
        }
        
    }
    
    fileprivate func setupNoti() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.gotoSelectType(_ :)), name: NSNotification.Name(rawValue: "SELECTTYPE"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.reloadData), name: Notification.Name(rawValue:"ISLOGIN"), object: nil)
        
    }
    
    // MARK: - 设置UI
    @objc fileprivate func reloadData() {
        if userDefault.integer(forKey: "bussinessType") == 1  {
            TYPE = userDefault.integer(forKey: "bussinessType")
        }
        
        if TYPE == 1 { // 技师
            rightItem?.isHidden = false
            topicView?.isHidden = true
            detailBtn.isHidden = true
            
        }
        
        if TYPE == 0 { // 商家
            rightItem?.isHidden = true
            topicView?.isHidden = false
            detailBtn.isHidden = false
            // 9宫格
            setupContentView()
            // 环球头条
            setupTopicView()
            
            self.headRefresh(orderResult.order, isRefreshing: false, mark: 0)
            
        }
    }
    
    // 9宫格布局
    fileprivate func setupContentView() {
        view.addSubview(contentView)
        contentView.backgroundColor = UIColor(r: 246, g: 246, b: 246)
        contentView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.storeNameView.snp.bottom).offset(46 * HEIGHT_SCALE)
        }
        
        let bgImageView = UIImageView(imageName: "jiugongge")
        bgImageView.isUserInteractionEnabled = true
        contentView.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(HEIGHT_SCALE * 685/2.0)
        }
        
        var btnArray = [UIButton]()
        for index in 0..<9 {
            let btn = UIButton(type: .custom)
            btn.tag = 10000 + index
            btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
            contentView.addSubview(btn)
            
            let row = index/3
            let cols = index%3
            let btnW = kScreenW / 3
            let btnH = (341/3.0) * kScreenH / 667.0
            btn.frame = CGRect(x: CGFloat(cols) * btnW, y: CGFloat(row) * btnH, width: btnW, height: btnH)
            btn.backgroundColor = UIColor.clear
            btnArray.append(btn)
        }
        
        nopayLabel.frame = CGRect(x: kScreenW/3/2 + 15, y: (341/3/2 - 30)*kScreenH / 667, width: 25*HEIGHT_SCALE, height: 15)
        contentView.addSubview(nopayLabel)
        
        let quitBtn = UIButton(type: .system)
        quitBtn.setTitle("退出登录", for: .normal)
        quitBtn.setTitleColor(UIColor(r:0, g:184, b:255), for: .normal)
        quitBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        quitBtn.layer.borderColor = UIColor(r:0, g:184, b:255).cgColor
        quitBtn.layer.masksToBounds = true
        quitBtn.layer.borderWidth = 1
        quitBtn.addTarget(self, action: #selector(quitBtnClick), for: .touchUpInside)
        contentView.addSubview(quitBtn)
        quitBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(btnArray.last!.snp.bottom).offset(40 * HEIGHT_SCALE)
            make.width.equalTo(120)
        }
    }
    
    // 环球头条
    fileprivate func setupTopicView() {
        
        let topicView = UIView()
        topicView.backgroundColor = UIColor.white
        view.addSubview(topicView)
        self.topicView = topicView
        topicView.snp.makeConstraints { (make) in
            make.left.right.equalTo(storeNameView)
            make.top.equalTo(storeNameView.snp.bottom)
            make.height.equalTo(36 * HEIGHT_SCALE)
        }
        
        let hLabel = UILabel()
        topicView.addSubview(hLabel)
        hLabel.snp.makeConstraints { (make) in
            make.left.equalTo(topicView).offset(20)
            make.centerY.equalToSuperview()
        }
        
        let attribute = NSMutableAttributedString(string: "环球头条")
        attribute.addAttributes([NSForegroundColorAttributeName: UIColor(r:0, g:184, b:255)], range: NSMakeRange(0, 2))
        hLabel.attributedText = attribute
        hLabel.font = UIFont.systemFont(ofSize: 13*HEIGHT_SCALE)
        
        let laba = UIImageView(imageName: "laba")
        topicView.addSubview(laba)
        laba.snp.makeConstraints { (make) in
            make.left.equalTo(hLabel.snp.right).offset(5)
            make.centerY.equalToSuperview()
        }
        
        topicView.addSubview(redianLabel)
        redianLabel.textAlignment = NSTextAlignment.center
        redianLabel.snp.makeConstraints { (make) in
            make.left.equalTo(laba.snp.right).offset(5*WIDTH_SCALE)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 30*WIDTH_SCALE, height: 20*HEIGHT_SCALE))
        }
        
        let label = SXMarquee(frame: CGRect(x: 145*WIDTH_SCALE, y: 3*HEIGHT_SCALE, width: kScreenW - 145*WIDTH_SCALE, height: 30 * HEIGHT_SCALE), speed: .mediumSlow, msg: "", bgColor: UIColor.white, txtColor: UIColor.gray)
        label?.changeLabel(UIFont.systemFont(ofSize: 13*HEIGHT_SCALE))
        label?.start()
        topicView.addSubview(label!)
//        DZYLog(label?.frame)
        marquee = label
    }
}

// MARK: - data
extension MainViewController {
    
    // 头条数据请求
    fileprivate func setupAnimation() {
        if TYPE == 0 {
            NetworkTools.shareInstance.requestData(Base_url + Get_store_detailes_url, .get, [:], { (json, isSuccess) in
                
                if isSuccess == true {
                    let data = JSON(json)
//                    DZYLog(data)
                    
                    let orderamout = data["noPay"]
                    if orderamout.intValue > 99 {
                        self.nopayLabel.text = "99+"
                    } else {
                        self.nopayLabel.text = orderamout.stringValue
                    }
                    
                    if data["success"].boolValue == true {
                        let marqueeArray = data["headLine"].arrayObject
                        var contentArray = [String]()
                        var typeArray: [String] = []
                        var linkArray = [String]()
                        var titleArray = [String]()
                        
                        for obj in marqueeArray! {
                            let dict = obj as! Dictionary<String, Any>
                            contentArray.append(dict["title"] as? String ?? "骏马环球名车欢迎您!")
                            typeArray.append(dict["type"] as? String ?? "公告")
                            linkArray.append(dict["link"] as? String ?? "")
                            titleArray.append(dict["type"] as? String ?? "")
                        }
                        self.marquee?.contentArr = contentArray
                        self.marquee?.linkArr = linkArray
                        self.marquee?.titleArr = titleArray
                        
                        self.marquee?.block = { (index) in
                            self.changeText(str: typeArray[index])
                        }
                        
                        self.marquee?.changeTapAction({ (link, title) in
                            if link == "" || link == nil {
                                
                            } else {
                                let webVc = WebViewController()
                                webVc.link = link!
                                webVc.title = "环球\(title!)"
                                self.navigationController?.pushViewController(webVc, animated: true)
                            }
                        })
                    }
                }
            })
        }
    }
    
    fileprivate func changeText(str: String) {
        redianLabel.layer.borderColor = UIColor.red.cgColor
        redianLabel.layer.borderWidth = 0.5
        redianLabel.text = str
        redianLabel.font = UIFont.systemFont(ofSize: 11 * HEIGHT_SCALE)
        redianLabel.textColor = UIColor.red
            
    }
    
    fileprivate func headRefresh(_ orderRes: String, isRefreshing: Bool, mark: Int) {
        
        showLoading()
        let URL = Base_url + (TYPE == 1 ? getHomeTec: STORE_DETAILS_API)
        
        NetworkTools.shareInstance.requestData(URL + orderRes, .get, [:]) { (json, isSuccess) in
            
            self.hideLoading()
            switch isSuccess {
            case true :
                let data = JSON(json)
                
//                DZYLog(data)
                
                guard let dict = data["storeDetailes"].dictionaryObject else {
                    return
                }

                self.storeDetailModel = HomeStoreDetailModel.mj_object(withKeyValues: dict)
                
                self.setupTopicViewTitles()
                
                // 可以有多种解析方式 可自己转换  也可以结合SwiftyJSON  
                // 字典转模型 可以自己转 也可以用MJExtension去转
//                let dict = data["storeDetailes"] as? [String: Any]
                
//                guard let resultDict = json as? [String: Any] else { return }
//                guard let detailDict = resultDict["storeDetailes"] as? [String : Any] else {return}
//                
//                let model = HomeStoreDetailModel(dict: detailDict)
            
            case false:
                self.showHUD(.failure, text: "获取数据失败")
            }
        }
    }
    
    // 给topicView属性赋值
    fileprivate func setupTopicViewTitles() {
        
        guard let imageURL = storeDetailModel?.avatar_img_url else {
            return
        }
        storeIcon.setImage(Base_url + imageURL, "")
        storeNameLabel.text = storeDetailModel?.store_name
        storeNameLabel.font = UIFont.boldSystemFont(ofSize: 18*HEIGHT_SCALE)
        
        let nameWidth: CGFloat = (StringSize((storeDetailModel?.store_name)! as NSString, fontSize: 18*HEIGHT_SCALE).width + 10 < kScreenW - 140*WIDTH_SCALE) ? StringSize((storeDetailModel?.store_name)! as NSString, fontSize: 18*HEIGHT_SCALE).width + 10 : kScreenW - 140*WIDTH_SCALE
        
        guard let starCount = storeDetailModel?.avg else {
            return
        }
        starView.setStar(CGFloat(starCount))
        // 设置分数
        setupStarLabelText(storeDetailModel?.avg as! CGFloat)
    
        if TYPE != 1 {
            
            if storeDetailModel?.level == nil {
                storeType.backgroundColor = UIColor.clear
            } else {
                storeType.text = storeDetailModel?.level
                storeType.backgroundColor = UIColor.white
            }
            // 设置年月日订单数
            setupBtnLabelTitle((storeDetailModel?.day_order)!, monthOrderCount: (storeDetailModel?.month_order)!, totalOrderCount: (storeDetailModel?.total_order)!)
            
        }
    }
    
    fileprivate func setupStarLabelText(_ startCount: CGFloat) {
     
        let text = NSString.init(format: "%.1f", startCount) as String + "分"
        let starText = NSMutableAttributedString(string: text)
        starText.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14*HEIGHT_SCALE), range: NSMakeRange(0, 3))
        starText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 10*HEIGHT_SCALE), range: NSMakeRange(3, 1))
        starText.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, starText.length))
        starLabel.attributedText = starText
    }
    
    fileprivate func setupBtnLabelTitle(_ dayOrderCount: Int, monthOrderCount: Int, totalOrderCount: Int) {
        
        let Text = "今日" + String(dayOrderCount) + "单, 本月" + String(monthOrderCount) + "单, 累计" + String(totalOrderCount) + "单. 查看详情点击"
        let detailText = NSMutableAttributedString(string: Text)
        
        detailText.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 10*HEIGHT_SCALE), range: NSMakeRange(0, detailText.length))
        detailText.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, detailText.length))
        
        detailText.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14*HEIGHT_SCALE), range: NSMakeRange(2, String(dayOrderCount).characters.count))
        detailText.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14*HEIGHT_SCALE), range: NSMakeRange(7+String(dayOrderCount).characters.count, String(monthOrderCount).characters.count))
        detailText.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14*HEIGHT_SCALE), range: NSMakeRange(detailText.length - 9 - String(totalOrderCount).characters.count, String(totalOrderCount).characters.count))
        
        detailText.addAttribute(NSForegroundColorAttributeName, value: RGBA(255, g: 202, b: 55, a: 1), range: NSMakeRange(2,String(dayOrderCount).characters.count))
        detailText.addAttribute(NSForegroundColorAttributeName, value: RGBA(255, g: 202, b: 55, a: 1), range: NSMakeRange(7+String(dayOrderCount).characters.count,String(monthOrderCount).characters.count))
        detailText.addAttribute(NSForegroundColorAttributeName, value: RGBA(255, g: 202, b: 55, a: 1), range: NSMakeRange(detailText.length-9-String(totalOrderCount).characters.count,String(totalOrderCount).characters.count))
        btnTitleLabel.attributedText = detailText
    }
    
}

// MARK: - event
extension MainViewController {
    
    @objc fileprivate func rightBarItemClick() {
        DZYLog("右侧按钮点击")
    }
    
    // 左上角按钮事件
    @objc fileprivate func gotoSelectType(_ type: Notification) ->() {
        
    }
    
    // 订单详情点击
    @objc fileprivate func detailBtnClick() {
        navigationController?.pushViewController(OrderMessageInfoViewController(), animated: true)
        
    }
    
    // 9宫格事件点击
    @objc fileprivate func btnClick(sender: UIButton) {
       
        switch sender.tag - 10000 {
        case 0: // 我的订单
            navigationController?.pushViewController(MyOrderViewController(), animated: true)
        case 1: // 个人资料
            navigationController?.pushViewController(MyInfoViewController(), animated: true)
        case 2: // 商家二维码
            navigationController?.pushViewController(QRViewController(), animated: true)
        case 3: // 收入明细
            navigationController?.pushViewController(MyIncomeViewController(), animated: true)
        case 4: // 兑换码
            homeAdView.showAlert()
            homeAdView.clickHandler = { (isPingan: Bool) in
                if isPingan {
                    self.navigationController?.pushViewController(ExchangeViewController(), animated: true)
                } else {
                    self.navigationController?.pushViewController(RenbaoViewController(), animated: true)
                }
            }
            
            break;
        case 5: // 停止营业
            navigationController?.pushViewController(CloseShopViewController(), animated: true)
        case 6: // 配置服务项
            navigationController?.pushViewController(CSIViewController(), animated: true)
        case 7: // 联系客服
            connectToService()
        case 8: // 分享app
            showHUD(.success, text: "加强", animated: true, afterDelay: 1, completionBlock: {
                DZYLog("1秒过了")
            })
        default: break
            
        }
    }
    
    @objc fileprivate func quitBtnClick() {
        
        let cookieStorage: HTTPCookieStorage = HTTPCookieStorage.shared
        let cookies = cookieStorage.cookies
        TYPE = 0
        for tempCookie: HTTPCookie in cookies! {
            cookieStorage.deleteCookie(tempCookie)
        }
        
        present(LoginViewController(), animated: true, completion: nil)
    }
}

// MARK: - 自定义方法
extension MainViewController {
    
    fileprivate func connectToService() {
        
        let alert = UIAlertController(title: "环球名车", message: "拨打电话联系客服", preferredStyle: .alert)
        let cancel = UIAlertAction(title: "取消", style: .default) { (action) in
            DZYLog("点击了取消")
        }
        let phone = UIAlertAction(title: "确定", style: .default) { (action) in
            UIApplication.shared.openURL(URL(string: "tel://4006989566")!)
        }
        alert.addAction(cancel)
        alert.addAction(phone)
        present(alert, animated: true, completion: nil)
    }
}

// MARK: - 判断是否已经登录
extension MainViewController {
    
    fileprivate func checkAutoLogin() {
        
        let vc = LoginViewController()
        present(vc, animated: true, completion: nil)
        
//        let userDefault = UserDefaults.standard
        if let userDict = UserDefaults.User.storeValue(forkey: .userInfo) {
            let key = (userDict as AnyObject).allKeys.first as! String
            if (userDict as AnyObject)[key] as! String != "" {
                let pwd = (userDict as AnyObject)[key] as! String
                UserAccount.login(withUsername: key, password: pwd, displayViewController: vc, complection: {_ in })
            } else {
                ProgressHUD.dismiss()
            }
        }
    }
}
